﻿#include "MainWidget.h"
#include "ui_MainWidget.h"
#include "CommonFunc.h"
#include <QTimer>
#include "DataInfo.h"
#include "ExitDialog.h"
#include <QCloseEvent>

MainWidget::MainWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::MainWidget)
{
    ui->setupUi(this);

    createNetworkAccessManager(this);

    QTimer *timer = new QTimer(this);
    connect(timer, &QTimer::timeout, [](){
        updateAllMessageInfo();
    });

    appendTypeToFunc(XUI_Login, [=](){
        ui->stackedWidget->setCurrentIndex(1);
        g_iProductLineID = -1;
        ui->gateWayManageWidget->clearGateWayInfo();
        g_iGateWayID = -1;
        ui->deviceManageWidget->clearDeviceData();
        ui->abnormalManageWidget->clearAbnormalData();
        ui->speedManageWidget->clearSpeedData();
        timer->start(30000);
    });

    appendTypeToFunc(XUI_Logout, [=](){
        ui->stackedWidget->setCurrentIndex(0);
        g_person_id = -1;
        timer->stop();
    });

    appendTypeToFunc(XUI_AreaManage, [=](){
        ui->stackedWidget->setCurrentWidget(ui->areaManageWidget);
        g_iProductLineID = -1;
        ui->gateWayManageWidget->clearGateWayInfo();
    });

    appendTypeToFunc(XUI_DeviceManage, [=](){
        ui->stackedWidget->setCurrentWidget(ui->deviceManageWidget);
    });

    appendTypeToFunc(XUI_AbnormalManage,
       std::bind(&QStackedWidget::setCurrentWidget, ui->stackedWidget, ui->abnormalManageWidget));

    appendTypeToFunc(XUI_ShowSpeed,
       std::bind(&QStackedWidget::setCurrentWidget, ui->stackedWidget, ui->speedManageWidget));

    appendTypeToFunc(XUI_GateWayManage, [=](){
        ui->stackedWidget->setCurrentWidget(ui->gateWayManageWidget);
        g_iGateWayID = -1;
        ui->deviceManageWidget->clearDeviceData();
        ui->abnormalManageWidget->clearAbnormalData();
        ui->speedManageWidget->clearSpeedData();
    });

    ui->stackedWidget->setCurrentIndex(0);
}

MainWidget::~MainWidget()
{
    delete ui;
}

void MainWidget::closeEvent(QCloseEvent *event)
{
    ExitDialog exit;
    int leftGap = 100;
    exit.setGeometry(this->x() + leftGap, this->y() + 20 + this->height() / 3,
                     this->width() - leftGap * 2, this->height() / 5);
    if (exit.exec())
    {
        event->accept();
    }
    else{
        event->ignore();
    }
}
